
import { onRoute, routeUrl } from '../common/Router';
import axios from 'axios';
import { PageCtl } from '../common/PageCtl';
import { getOffsetTop, htmlEncode } from '../common/util';

async function apiNews(pagesize, pagenum) {
    try {
        let res = await axios.get(`https://www.fastmock.site/mock/d8c33ca26a546a3c9be78ee13f714990/t1-0fficial/api/news?page=${pagenum}&page_size=${pagesize}`);
        if (res.status !== 200) return { code: res.status, desc: res.statusText }
        return res.data;
    } catch (err) {
        return { code: 500, desc: err?.message ?? err };
    }
}
async function apiNewsDetail(newsCode) {
    try {
        let res = await axios.get(`https://www.fastmock.site/mock/d8c33ca26a546a3c9be78ee13f714990/t1-0fficial/api/news/${newsCode}`);
        if (res.status !== 200) return { code: res.status, desc: res.statusText }
        return res.data;
    } catch (err) {
        return { code: 500, desc: err?.message ?? err };
    }
}

function showError(errTplStr, targetEl, errorCode, errorDesc) {
    console.error(errorCode, errorDesc);
    targetEl.innerHTML = errTplStr
        .replace(/\{error-code\}/ig, errorCode)
        .replace(/\{error-desc\}/ig, errorDesc);
}

async function loadNews(pagesize, pagenum, itemTplStr, newsSkeletonTplStr, errTplStr, targetEl, pageCtl, scrollTo) {

    var html = '';
    for (let i = 0; i < pagesize; i++) {
        html += newsSkeletonTplStr;
    }
    targetEl.innerHTML = html;
    //await new Promise(r => setTimeout(r, 1000));

    let ret = await apiNews(pagesize, pagenum);
    if (ret.code !== 200) {
        return showError(errTplStr, targetEl, ret.code, ret.desc);
    }
    let newsArr = ret.data;
    html = '';
    newsArr.map(news => {
        html += itemTplStr
            .replace(/\{data-src\}/ig, 'data-src')
            .replace(/\{img\}/ig, htmlEncode(news.img))
            .replace(/\{title\}/ig, htmlEncode(news.title))
            .replace(/\{keyword\}/ig, htmlEncode(news.keyword))
            .replace(/\{code\}/ig, htmlEncode(news.code))
            .replace(/\{code\-encode\}/ig, encodeURIComponent(news.code))
    });
    targetEl.innerHTML = html;
    pageCtl.renderPageCtl(ret.meta.per_page, ret.meta.current_page, ret.meta.total);
    if (scrollTo) {
        //平滑滚过去
        window.scroll({
            left: 0,
            top: getOffsetTop(targetEl),
            behavior: 'smooth'
        });
    }
}

export function initNews() {
    onRoute(/\/news\.html/ig, function (url, query) {
        let newsItemTpl = document.getElementsByClassName('news-item-tpl')[0];
        let newsSkeletonTpl = document.getElementsByClassName('news-skeleton-tpl')[0];
        let newsListEl = document.getElementsByClassName('news-list')[0];
        let newsErrTpl = document.getElementsByClassName('news-error-tpl')[0];
        let pageCtlTpl = document.getElementsByClassName('page-ctl-tpl')[0];
        let pageCtlTarget = document.getElementsByClassName('page-ctl')[0];
        if (!newsItemTpl || !newsListEl || !newsErrTpl || !pageCtlTpl || !pageCtlTarget) {
            throw new Error('match router /news.html, but not foud .news-item-tpl or others');
        }
        var pageCtl = new PageCtl(pageCtlTpl, pageCtlTarget, query.pageSize, query.pageNum, 0);
        pageCtl.onCtlPage((pageSize, pageNum) => {
            loadNews(pageSize, pageNum, newsItemTpl.innerHTML, newsErrTpl.innerHTML, newsListEl, pageCtl, true);
            routeUrl(`news.html?pageSize=${pageSize}&pageNum=${pageNum}`);
        });
        loadNews(pageCtl.pageSize, pageCtl.pageNum, newsItemTpl.innerHTML, newsSkeletonTpl.innerHTML, newsErrTpl.innerHTML, newsListEl, pageCtl);
    });
    onRoute(/\/news\-details\.html/ig, async function (url, query) {
        let newsTitle = document.getElementsByClassName('news-title')[0];
        let newsCnt = document.getElementsByClassName('news-content')[0];
        if (!newsCnt) {
            throw new Error('match router /news-details.html, but not foud .news-content or others');
        }
        let newsCode = query.code;
        if (!newsCode) {
            document.title = newsTitle.innerHTML = 'query code is empty!';
            newsCnt.innerHTML = '';
            return;
        }
        let ret = await apiNewsDetail(newsCode);
        if (ret.code !== 200) {
            document.title = newsTitle.innerHTML = `获取新闻失败了`;
            newsCnt.innerHTML = `[${ret.code}] ${ret.desc}`;
            return;
        }
        newsCnt.innerHTML = ret.data.text;
        newsTitle.innerHTML = ret.data.title;
        document.title = ret.data.title;
    });
}
